//
//  ViewController.m
//  StudySceneKit
//
//  Created by Moyun on 2017/8/30.
//  Copyright © 2017年 Cmall. All rights reserved.
//

#import "ViewController.h"
#import <ModelIO/ModelIO.h>
#import <SceneKit/SceneKit.h>
#import <SceneKit/ModelIO.h>
#import "PrimittivesScene.h"

static CGFloat const tipsH = 64;

@interface ViewController (){
    CGFloat _scale;
    UILabel *_tipsLabel;
    
    NSInteger _curIndex;
}

@property (strong, nonatomic) PrimittivesScene *scene;
@property (weak, nonatomic) IBOutlet UILabel *changeColorLabel;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    SCNView *view = (SCNView *)self.view;
    self.scene = [[PrimittivesScene alloc] init];
    view.scene = self.scene;
    view.backgroundColor = [UIColor whiteColor];
 
    view.allowsCameraControl = true;//允许手势加护
    view.showsStatistics = true;
//    view.autoenablesDefaultLighting = true;
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
    
    NSMutableArray *gestureRecognizers = [NSMutableArray array];
    [gestureRecognizers addObject:tapGesture];
//    [gestureRecognizers addObject:panGesture];
//    [gestureRecognizers addObject:pinchGesture];
    [gestureRecognizers addObjectsFromArray:view.gestureRecognizers];
    view.gestureRecognizers = gestureRecognizers;
    
    _scale = 0.65;
    [self.scene.rootNode runAction:[SCNAction scaleTo:_scale duration:0]];
    
    _tipsLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, -tipsH, self.view.bounds.size.width, tipsH)];
    _tipsLabel.font = [UIFont systemFontOfSize:18];
    _tipsLabel.numberOfLines = 0;
    _tipsLabel.backgroundColor = [UIColor redColor];
    _tipsLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_tipsLabel];
    
    UIButton *resetButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [resetButton setFrame:CGRectMake(CGRectGetWidth(self.view.frame) - 45 - 10, CGRectGetHeight(self.view.frame) - 45 - 20, 45, 45)];
    [resetButton setTitle:@"归位" forState:UIControlStateNormal];
    [resetButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [resetButton addTarget:self action:@selector(clickReset:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:resetButton];
    
    self.changeColorLabel.text = self.scene.colors.firstObject;
}

- (IBAction)changeColor:(id)sender {
    if ([sender isKindOfClass:[UIButton class]]) {
        UIButton *btn = (UIButton*)sender;
        btn.tag == 1 ? _curIndex ++ : _curIndex--;
        if (_curIndex < 0) {
            _curIndex = self.scene.colors.count-1;
        }else if (_curIndex >= self.scene.colors.count) {
            _curIndex = 0;
        }
        NSString *colorName = [self.scene.colors objectAtIndex:_curIndex];
        
        self.changeColorLabel.text = colorName;
        [self.scene reloadSeceneWithColorName:colorName];
    }
}

- (IBAction)changeLight:(id)sender {
    UIButton *btn = (UIButton*)sender;
    [self.scene changeSeceneLightEnvironment:btn.tag];
    [btn setTitle:btn.tag?@"换光(亮)":@"换光(暗)" forState:UIControlStateNormal];
    btn.tag = !btn.tag;
}
#pragma mark - 手势处理

- (void) handleTap:(UIGestureRecognizer*)gestureRecognize
{
    //去到SCNView
    // retrieve the SCNView
    SCNView *scnView = (SCNView *)self.view;
    
    //找到对应的node
    CGPoint p = [gestureRecognize locationInView:scnView];
    NSArray *hitResults = [scnView hitTest:p options:nil];
    
    if([hitResults count] > 0){
        // 找到第一个响应对象
        SCNHitTestResult *result = [hitResults objectAtIndex:0];
        
        // 拿到对象对应的素材，裁片
        SCNMaterial *material = result.node.geometry.firstMaterial;
        
        [SCNTransaction begin];
        [SCNTransaction setAnimationDuration:0.5];
        
        [SCNTransaction setCompletionBlock:^{
            [SCNTransaction begin];
            [SCNTransaction setAnimationDuration:0.5];
            
            material.emission.contents = [UIColor blackColor];
            
            [SCNTransaction commit];
        }];
        
        material.emission.contents = [UIColor redColor];
        
        [SCNTransaction commit];
    }
}

- (void) handlePan:(UIPanGestureRecognizer*)gestureRecognize
{
    //找到SCNView
    SCNView *scnView = (SCNView *)self.view;
    //拖动距离
    CGPoint point = [gestureRecognize translationInView:scnView];
    //模型节点
    SCNNode *node = self.scene.rootNode;
    //添加旋转
    [node runAction:[SCNAction rotateByX:0 y:point.x * 0.0005 z:0 duration:0]];
    
//    var newAngle = (Float)(translation.x)*(Float)(M_PI)/180.0
//    newAngle += currentAngle
//    
//    geometryNode.transform = SCNMatrix4MakeRotation(newAngle, 0, 1, 0)
//    
//    if(gestureRecognize.state == UIGestureRecognizerState.Ended) {
//        currentAngle = newAngle
//    }
}

- (void) handlePinch:(UIPinchGestureRecognizer*)gestureRecognize
{
    //获得 缩放量 加一个【灵敏度】
    CGFloat degree =  gestureRecognize.velocity > 0 ? 0.01 : 0.05 ;
    CGFloat scale = (gestureRecognize.scale -1) * _scale * degree + _scale;
    NSLog(@"==总量:%f==速度：%f",scale,gestureRecognize.velocity);
    if (scale > 0.75 || scale < 0.5) {
        if (_tipsLabel.tag == 0) {
            [self showTipsLabelWithMes:@"到达缩放边界！！！"];
        }
        return;
    }
    //模型节点
    SCNNode *node = self.scene.rootNode;
    [node runAction:[SCNAction scaleTo:scale duration:0]];
    _scale = scale;
}

#pragma mark - 归位，便于截图

- (void)clickReset:(UIButton*)btn{
    SCNNode *node = self.scene.rootNode;
    
    [node runAction:[SCNAction rotateToX:0 y:0 z:0 duration:0]];
    [node runAction:[SCNAction scaleTo:0.65 duration:0]];
}

#pragma mark - 温馨提示

- (void)showTipsLabelWithMes:(NSString*)msg{
    
    _tipsLabel.text = msg;
    _tipsLabel.tag = 1;
    [UIView animateWithDuration:0.5 delay:0 usingSpringWithDamping:0.5 initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _tipsLabel.transform = CGAffineTransformMakeTranslation(0, tipsH);
    } completion:^(BOOL finished) {
        [self performSelector:@selector(hideTipsLabel) withObject:nil afterDelay:2.0];
    }];
}

- (void)hideTipsLabel{
    [UIView animateWithDuration:0.5 delay:0.0 usingSpringWithDamping:1.0 initialSpringVelocity:0.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _tipsLabel.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        _tipsLabel.tag = 0;
    }];
}

@end
